package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"yzy6.26exam/api/request"
	"yzy6.26exam/golbal"
	"yzy6.26exam/internal/bao"
	"yzy6.26exam/internal/moble"
)

func Like(context *gin.Context) {
	var like request.Like
	if err := context.ShouldBind(&like); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    204,
			"message": "解析失败",
			"data":    err.Error(),
		})
		return
	}
	var likes moble.Like
	likes.UserId = like.UserId
	likes.VideoId = like.VideoId
	err := bao.FindOnce(&likes)
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    203,
			"message": "点赞失败",
			"data":    err.Error(),
		})
		return
	}
	var total int64
	golbal.DB.Model(&moble.Like{}).Where("video_id = ?", like.VideoId).Count(&total)
	if likes.Id == 0 {
		err := bao.Create(&likes)
		if err != nil {
			context.JSON(http.StatusOK, gin.H{
				"code":    203,
				"message": "点赞失败",
				"data":    total,
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code":    203,
			"message": "点赞成功",
			"data":    total + 1,
		})
		return
	} else {
		err := bao.Delete(&likes)
		if err != nil {
			context.JSON(http.StatusOK, gin.H{
				"code":    203,
				"message": "取消点赞失败",
				"data":    total,
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code":    203,
			"message": "取消点赞成功",
			"data":    total - 1,
		})
		return
	}
}
